/*
 * @Description: 
 * @Author: xuqi
 * @Github: https://github.com/knight-peter
 * @LastEditors: xuqi
 */
/**

 @Name：用户管理
 @Author：xuqipeter
 @Site：http://blog.xuziyu.cn/
    
 */

layui.extend({
  citypicker: '../assets/plugins/city-picker/city-picker'
}).define(function (exports) {
  layui.use(['citypicker', 'table', 'layer', 'm-utils', 'form', 'admin', 'view', 'UserModel'], function () {
    var $ = layui.$,
      table = layui.table,
      layer = layui.layer,
      admin = layui.admin,
      view = layui.view,
      form = layui.form,
      setter = layui.setter,
      baseUrl = setter.baseUrl,
      utils = layui['m-utils'],
      cityPicker = layui.citypicker,
      userModel = layui.UserModel;

    form.render();
    userModel.tableList = userModel._tableList()
    /* search重载table */
    form.on('submit(js-btn-table-search)', function (data) {
      let field = data.field;
      userModel.tableList.reload({
        where: field
      });
      return false;
    });
    table.on('toolbar(tableList)', function (obj) {
      switch (obj.event) {
        case 'add':
          _layerAdd();
          layer.full(userModel.layerFull);
          break;
      }
    });
    /*监听主页面table行工具栏*/
    var tableObj;
    table.on('tool(tableList)', function (obj) {
      tableObj = obj;
      const data = obj.data;
      const layEvent = obj.event;
      const tr = obj.tr;
      switch (layEvent) {
        case 'detail':
          _layerDetail(tableObj);
          layer.full(userModel.layerFull);
          break;
        case 'edit':
          _layerEdit(tableObj);
          layer.full(userModel.layerFull);
          break;
        case 'del':
          _layerDel(tableObj);
          break;
        case 'open_agent':
          _layerOpen(data, 'agent', true);
          break;
        case 'open_founder':
          _layerOpen(data, 'founder', true);
          break;
        case 'open_area_agent':
          _layerOpen(data, 'area_agent', true);
          break;
        case 'createAgentOrder':
          _layerOrder(tableObj, 'agent');
          layer.full(userModel.layerFull);
          break;
        case 'createAreaAgentOrder':
          _layerOrder(tableObj, 'area_agent');
          layer.full(userModel.layerFull);
          break;
        case 'bind_parent_number':
          _layerBindParentNumber(tableObj)
          break;
      }
    });
    /* 增加 */
    function _layerAdd() {
      userModel.layerFull = admin.popup({
        id: 'tableAdd',
        title: '新增用户',
        area: ['800px', '400px'],
        offset: 't',
        btn: ['提交', '取消'],
        btnAlign: 'c',
        maxmin: true,
        skin: 'myskin',
        yes: function (index, layero) {
          layer.confirm(`确定要新增吗？`, {
            icon: 3
          }, function (confirmIdx) {
            layer.close(confirmIdx);
            layero.find('[type="submit"]').trigger('click');
          })
        },
        success: function () {
          view(this.id).render('/g-popup/user__add').done(function () {
            utils.tplRender('popupTplUser', 'popupViewUser', {}, function () {
              form.render();
              var currentPicker = new cityPicker("#city-picker", {
                provincename: "provinceId",
                cityname: "cityId",
                districtname: "districtId",
                level: 'districtId', // 级别
              });
              currentPicker.setValue("");
            });
          })
        },
      });
    }
    /* 查看 */
    function _layerDetail(obj) {
      const data = obj.data
      userModel.layerFull = admin.popup({
        id: 'detail',
        title: `用户编号：<b>${data.number}</b> 的详情信息`,
        area: ['800px', '400px'],
        offset: 't',
        btn: ['关闭'],
        btnAlign: 'c',
        maxmin: true,
        skin: 'myskin',
        success: function () {
          view(this.id).render('g-popup/user__detail').done(function () {
            utils.tplRender('popupTplUser', 'popupViewUser', data);
          })
        }
      });
    }
    /* 编辑 */
    function _layerEdit(obj) {
      const data = obj.data
      userModel.layerFull = admin.popup({
        id: 'tableAdd',
        title: `用户编号：<b>${data.number}</b> 的详情信息`,
        area: ['800px', '400px'],
        offset: 't',
        btn: ['提交', '取消'],
        btnAlign: 'c',
        maxmin: true,
        skin: 'myskin',
        yes: function (index, layero) {
          layer.confirm(`确定要编辑 用户编号：<b>${data.number}</b> 吗？`, {
            icon: 3
          }, function (confirmIdx) {
            layer.close(confirmIdx);
            layero.find('[type="submit"]').trigger('click');
          })
        },
        success: function () {
          view(this.id).render('/g-popup/user__add').done(function () {
            utils.tplRender('popupTplUser', 'popupViewUser', data, function () {
              form.render();
            });
          })
        },
      });
    }
    /* 删除 */
    function _layerDel(obj) {
      const data = obj.data;
      const tr = obj.tr;
      // console.log(obj)
      layer.confirm(`确定要删除 用户编号：<b>${data.number}</b> 吗？`, {
        icon: 0
      }, function (confirmIdx) {
        layer.close(confirmIdx);
        tr.remove();
        layer.msg('删除成功', {
          icon: 1,
          itme: 1500
        })
      })
    }
    /* 直接开通董事,联创,区代 */
    function _layerOpen(obj, user_type, need) {
      const data = obj;
      let fieldData = {
        type: user_type,
        user_id: data.user_id,
        area_name: data.area_name || ''
      }
      console.log(obj, user_type, fieldData)
      let type_name = ''
      switch (user_type) {
        case 'agent':
          type_name = '董事'
          break;
        case 'founder':
          type_name = '联创'
          break;
        case 'area_agent':
          type_name = '区代'
          break;
      }

      if (need) {
        layer.confirm(`确定要开通${type_name}吗？`, {
          icon: 3
        }, function (confirmIdx) {
          layer.close(confirmIdx);
          if (fieldData.type === 'area_agent') {
            layer.close(userModel.layerFull);
            _layerChooseArea(fieldData)
          } else {
            userModel._openUser({
              fieldData
            })
          }
        })
      } else {
        if (fieldData.type === 'area_agent') {
          layer.close(userModel.layerFull);
          _layerChooseArea(fieldData)
        } else {
          userModel._openUser({
            fieldData
          })
        }
      }

    }
    /* 选择地区弹窗 */
    let layerChooseArea

    function _layerChooseArea(fieldData) {
      userModel.layerFull = admin.popup({
        id: 'chooseArea',
        title: `选择地区`,
        area: ['800px', '400px'],
        offset: 't',
        btn: ['提交', '取消'],
        btnAlign: 'c',
        maxmin: true,
        yes: function (index, layero) {
          layero.find('[type="submit"]').trigger('click');
        },
        success: function () {
          view(this.id).render('/g-popup/user__choose__area').done(function () {
            utils.tplRender('popupTplUserArea', 'popupViewUserArea', fieldData, function () {
              form.render();
              let currentPickerOrder3 = new cityPicker("#city-picker-order3", {
                provincename: "provincenameid3",
                cityname: "citynameid3",
                districtname: "districtnameid3"
              });
              currentPickerOrder3.setValue('');
            });
          })
        },
      });
    }
    /* 开通董事，总代的订单弹窗 */
    function _layerOrder(obj, type) {
      const data = obj.data
      let type_name = ''
      if (type === 'agent') {
        type_name = '董事'
        data.user_type = 'agent'
      }
      if (type === 'area_agent') {
        type_name = '区代'
        data.user_type = 'area_agent'
      }
      userModel.layerFull = admin.popup({
        id: 'tableAdd',
        title: `创建<b> ${data.realname} </b>的${type_name}订单`,
        area: ['800px', '400px'],
        offset: 't',
        btn: ['提交', '取消'],
        btnAlign: 'c',
        maxmin: true,
        skin: 'myskin',
        yes: function (index, layero) {
          layer.confirm(`确定要创建<b> ${data.realname} </b>的${type_name}订单吗？`, {
            icon: 3
          }, function (confirmIdx) {
            layer.close(confirmIdx);
            layero.find('[type="submit"]').trigger('click');
          })
        },
        success: function () {
          view(this.id).render('/g-popup/user__order__add').done(function () {
            utils.tplRender('popupTplUserOrder', 'popupViewUserOrder', data, function () {
              form.render();
              var currentPickerOrder = new cityPicker("#city-picker-order", {
                provincename: "provincenameid2",
                cityname: "citynameid2",
                districtname: "districtnameid2"
              });
              currentPickerOrder.setValue(data.receiver_area_name);
            });
          })
        },
      });
    }
    /* 绑定上级表单 */
    function _layerBindParentNumber(obj) {
      const data = obj.data
      layer.prompt({
        title: '请输入上级编号',
      }, function (value, index, elem) {
        let fieldData = {
          number: value,
          user_id: data.user_id
        }
        userModel._bindNumber({
          fieldData
        })
        layer.close(index);
      });
    }
    /* 提交表单 */
    form.on('submit(submitBtn)', function (res) {
      let fieldData = utils.formDataFilter(res.field) || '';
      console.log(fieldData)
      userModel._createUser({
        fieldData
      })
      return false;
    })
    /* 开通区代 */
    form.on('submit(submitBtnOpenAreaAgent)', function (res) {
      let fieldData = utils.formDataFilter(res.field) || '';
      console.log(fieldData)
      userModel._openUser({
        fieldData
      })
      return false;
    })
    /* 创建董事订单，创建区代订单 */
    form.on('submit(submitBtnOrder)', function (res) {
      let fieldData = utils.formDataFilter(res.field) || '';
      if (fieldData.user_type === 'agent') {
        userModel._createAgentOrder({
          fieldData,
          callback: function (res) {
            if (res.code === 200) {
              _layerOpen(fieldData, 'agent')
            }

          }
        })
      }
      if (fieldData.user_type === 'area_agent') {
        userModel._createAreaAgentOrder({
          fieldData,
          callback: function (res) {
            if (res.code === 200) {
              _layerOpen(fieldData, 'area_agent')
            }
          }
        })
      }
      return false;
    })
  })

  exports('m-user', {})
})